package vn.edu.ptithcm.pim.controller;

import vn.edu.ptithcm.pim.dom.Company;
import vn.edu.ptithcm.pim.dom.News;
import vn.edu.ptithcm.pim.dom.Resource;
import vn.edu.ptithcm.pim.dom.User;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import vn.edu.ptithcm.pim.constant.Constants;
import vn.edu.ptithcm.pim.constant.UrlConstants;
import vn.edu.ptithcm.pim.service.CompanyService;
import vn.edu.ptithcm.pim.service.NewsService;
import vn.edu.ptithcm.pim.service.ResourceService;
import vn.edu.ptithcm.pim.service.UserService;
import vn.edu.ptithcm.pim.util.ParamUtil;

@SuppressWarnings("deprecation")
public class HomePageController extends SimpleFormController {

	private CompanyService companyService;
	private UserService userService;
	private ResourceService resourceService;
	private NewsService newsService;
	private LocaleResolver localeResolver;

	Logger log = Logger.getLogger(HomePageController.class);

	public HomePageController() {
		super();
		setSessionForm(true);
		setCommandName("user");
		setCommandClass(User.class);
		setFormView(UrlConstants.HOME_PAGE_URL);
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		return ParamUtil.getObject(request, "user", new User());
	}

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		User user = (User) command;
		if (userService.isLogin(user.getLoginname(), user.getPassword(), null)) {
			request.getSession().setAttribute(Constants.LOGIN_NAME,
					user.getLoginname());

			String redirectLink = (String) request.getSession().getAttribute(
					"redirectLink");

			log.info("HomePageController || redirectLink : " + redirectLink);

			if (redirectLink != null) {
				request.getSession().removeAttribute("redirectLink");
				setSuccessView(UrlConstants.REDIRECT_PREFIX + redirectLink);
			} else {
				setSuccessView(UrlConstants.REDIRECT_PREFIX
						+ UrlConstants.MY_HOME_PAGE_URL + UrlConstants.HTM);
			}
		} else {
			errors.rejectValue("password", "signin.message.failed");
			return showForm(request, response, errors);
		}
		return super.onSubmit(request, response, command, errors);
	}

	@Override
	protected ModelAndView showForm(HttpServletRequest request,
			HttpServletResponse response, BindException errors)
			throws Exception {
		Map<String, Object> bean = new HashMap<String, Object>();
		String id = ParamUtil.getString(request, "id", "");
		bean.put("id", id);
		boolean isSignedIn = userService.isSignedIn(request);

		Company company = (Company) companyService.getAll().get(0);
		bean.put("company", company);

		String newsDetailLink = "";
		if (isSignedIn) {
			bean.put("isSigned", true);
			String loginName = userService.getCurrentLogin(request);
			bean.put("isAdmin", userService.isAdmin(loginName));
			bean.put("user", userService.findByLoginName(loginName));
			newsDetailLink = "articleDetail.htm?id=";
		} else {
			bean.put("isSigned", false);
			newsDetailLink = "homeNewsDetail.htm?id=";
		}

		bean.put("announcementLinks",
				getNewsLinksByType("announcement", newsDetailLink));
		bean.put("upcomingEventLinks",
				getNewsLinksByType("upcomingevent", newsDetailLink));

		String locale = ParamUtil.getString(request, "locale", "");
		if (!locale.isEmpty()) {
			getLocaleResolver()
					.setLocale(request, response, new Locale(locale));
		} else {
			locale = getLocaleResolver().resolveLocale(request).getLanguage();
		}
		request.setAttribute("locale", locale);

		List<Resource> slideShowList = resourceService
				.getResourcesForSlideShow(5);
		int slideShowCount = slideShowList.size();

		bean.put("slideShowCount", slideShowCount);
		bean.put("slideShowList", slideShowList);

		request.setAttribute("bean", bean);

		return super.showForm(request, response, errors);
	}

	public LocaleResolver getLocaleResolver() {
		return localeResolver;
	}

	public void setLocaleResolver(LocaleResolver localeResolver) {
		this.localeResolver = localeResolver;
	}

	public CompanyService getCompanyService() {
		return companyService;
	}

	public void setCompanyService(CompanyService companyService) {
		this.companyService = companyService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public ResourceService getResourceService() {
		return resourceService;
	}

	public void setResourceService(ResourceService resourceService) {
		this.resourceService = resourceService;
	}

	public NewsService getNewsService() {
		return newsService;
	}

	public void setNewsService(NewsService newsService) {
		this.newsService = newsService;
	}

	private String getNewsLinksByType(String type, String newsDetailLink) {
		try {
			StringBuilder links = new StringBuilder();
			List<News> newsList = newsService.getNewNewsByType(type);

			for (News news : newsList) {
				links.append("<img src='/pim/images/bullet.jpg' alt=''/>&nbsp;");

				links.append("<a class='hotnews' href='");
				links.append(newsDetailLink + news.getNewsid());
				links.append("'>");

				String title = news.getTitle();
				if (title.length() > 40) {
					title = title.substring(0, 40) + "...";
				}

				links.append(title);
				links.append("</a>&nbsp;&nbsp;");

				links.append("<img src='/pim/images/new.gif' alt=''/>");

				links.append("<br/>");
			}
			return links.toString();
		} catch (RuntimeException re) {
			throw re;
		}
	}
}
